<?php

namespace App\Http\Controllers\Api;

use App\ActivityGroupPrice;
use App\Classify;
use App\Comment;
use App\CommentImg;
use App\Goods;
use App\GoodsBanner;
use App\GoodsImg;
use App\GoodSpu;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\OrderItem;
use App\Orders;
use App\ShopCart;
use App\ShowGoods;
use App\User;
use App\UserInfo;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class GoodsController extends Controller
{
    /**
     * 获取商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsList(Request $request){
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page       = !is_null($request->get('page')) ? $request->get('page') : 0;
        $classifyId = !is_null($request->get('classify_id')) ? $request->get('classify_id') : 0;
        $goodsName  = $request->get('goods_name');
        $type       = $request->get('type');


        /** @var Goods $Goods*/
        $allGoods = DB::table('goods')->whereIsShop(1)->whereNull('deleted_at');

        if($classifyId != 0 && $classifyId != '') {
            $allGoods->whereClassifyId($classifyId);
        }

        if(!is_null($goodsName) && $goodsName != ''){
            $allGoods = $allGoods->where('name','like','%'.trim($goodsName).'%');
        }

        if(!is_null($type) && $type != ''){
            $allGoods = $allGoods->where('type','like','%'.$type.'%');
        }


            $allGoods = $allGoods->orderBy('sort','asc')->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();

        if(count($allGoods) > 0){
            foreach($allGoods as $Goods){
                $Goods->thumb_Url = FileManager::getImgUrl($Goods->thumb_id);
            }
        }

        /** @var ShowGoods $showGoods */
        $showGoods = ShowGoods::whereId(1)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $allGoods,'show_goods' => $showGoods ? $showGoods->show_goods_one : null]);
    }

    /**
     * 获取商品分类（含二级）
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsClassify(Request $request){
        /** @var Classify $classify */
        $classifies = Classify::wherePid(0)->orderBy('sort','asc')->orderBy('created_at','desc')->get();
        if(count($classifies) > 0){
            foreach($classifies as $classify){
                $SecondaryClassify = Classify::wherePid($classify->id)->orderBy('sort','asc')->orderBy('created_at','desc')->get();
                $classify->secondary_classify = $SecondaryClassify;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $classifies]);
    }

    /**
     * 获取商品详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsDetails(Request $request){
        $goodsId = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $activityGroupId = !is_null($request->get('activity_group_id')) ? $request->get('activity_group_id') : 0;

        /** @var Goods $goodsDetails */
        $goodsDetails = Goods::whereId($goodsId)->whereIsShop(1)->first();
        if($goodsDetails){
            $goodsDetails->thumb_url = FileManager::getImgUrl($goodsDetails->thumb_id);

            /** @var GoodsBanner $goodsBanner */
            $goodsBanners = GoodsBanner::whereGoodId($goodsDetails->id)->orderBy('sort','asc')->orderBy('created_at','desc')->get();
            $goodsBannerUrls = array();
            if(count($goodsBanners) > 0){
                foreach($goodsBanners as $goodsBanner){
                    $goodsBannerUrl = FileManager::getImgUrl($goodsBanner->img_id);
                    array_push($goodsBannerUrls,$goodsBannerUrl);
                }
            }

            $goodsDetails->goods_banner = $goodsBannerUrls;

            /** @var GoodsImg $goodsImage */
            $goodsImages = GoodsImg::whereGoodId($goodsDetails->id)->get();
            $goodsImageUrls = array();
            if(count($goodsImages) > 0){
                foreach($goodsImages as $goodsImage){
                    $goodsImageUrl = FileManager::getImgUrl($goodsImage->thumb_id);
                    array_push($goodsImageUrls,$goodsImageUrl);
                }
            }

            /** @var GoodSpu $goodSpu */
            $goodSpuList = GoodSpu::whereGoodsId($goodsDetails->id)->whereStatus(1)->orderBy('sort','asc')->get();

            if($goodsDetails->type == 'group'){
                if(count($goodSpuList) > 0){
                    foreach($goodSpuList as $goodSpu){
                        /** @var ActivityGroupPrice $activityGroup */
                        $activityGroup = ActivityGroupPrice::whereActivityGroupId($activityGroupId)->whereGoodsId($goodsDetails->id)->whereGoodsSpuId($goodSpu->id)->first();
                        if($activityGroup) {
                            $goodSpu->many_price = $activityGroup->many_price;
                        }else{
                            $goodSpu->many_price = $goodSpu->price;
                        }
                    }
                }
            }

            $goodsDetails->detailed_description      = $goodsImageUrls;
            $goodsDetails->goods_spu_info            = $goodSpuList;
        }else{
            return response()->json(['level' => 'error','message' => '该商品已下架']);
        }

        return response()->json(['level' => 'success','message' => '获取商品详情','data' => $goodsDetails]);
    }

    /**
     * 添加购物车接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function addShopCart(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        if(is_null($user->phone) || $user->phone == '')
            return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']);

        $goodsId  = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $num      = !is_null($request->get('num')) ? $request->get('num') : 1;
        $goodsSpu = !is_null($request->get('goods_spu_id')) ? $request->get('goods_spu_id') : 0;

        /** @var Goods $thisGoods */
        $thisGoods = Goods::whereId($goodsId)->whereIsShop(1)->first();
        if(!$thisGoods)
            return response()->json(['level' => 'error','message' => '该商品已下架']);

        if(is_null($goodsSpu) || $goodsSpu == 0)
            return response()->json(['level' => '请选择规格']);

        /** @var GoodSpu $thisGoodsSpu */
        $thisGoodsSpu = GoodSpu::whereId($goodsSpu)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
        if(!$thisGoodsSpu)
            return response()->json(['level' => 'error','message' => '该商品规格不存在']);

        /** @var ShopCart $newShopCart */
        $newShopCart = ShopCart::whereUserId($user->id)->whereGoodsId($thisGoods->id)->whereGoodSpuId($thisGoodsSpu->id)->first();
        if($newShopCart){
            if($num == -1 && $num != ''){
                $resultNum = (int)$newShopCart->num + (int)$num;
                $newShopCart->num          = $resultNum;
                $newShopCart->amount_money = (float)$newShopCart->unit_price * $resultNum;
                $newShopCart->save();

                if($newShopCart->num < 1){
                    $newShopCart->delete();
                }
            }else if($num == 1 && $num != ''){
                if($thisGoodsSpu->stock < $num || $thisGoodsSpu->stock == 0)
                    return response()->json(['level' => 'error','message' => '商品库存不足']);

                $resultNum = (int)$newShopCart->num + (int)$num;
                $newShopCart->num          = $resultNum;
                $newShopCart->amount_money = (float)$newShopCart->unit_price * $resultNum;
                $newShopCart->save();
            }
        }else{
            if($num == -1 || $num == '')
                return response()->json(['level' => 'error','message' => '操作错误']);

            if($thisGoodsSpu->stock < $num || $thisGoodsSpu->stock == 0)
                return response()->json(['level' => 'error','message' => '商品库存不足']);

            $newShopCart = new ShopCart();
            $newShopCart->user_id      = $user->id;
            $newShopCart->goods_id     = $thisGoods->id;
            $newShopCart->good_spu_id  = $thisGoodsSpu->id;
            $newShopCart->unit_price   = $thisGoodsSpu->price;
            $newShopCart->num          = $num;
            $newShopCart->amount_money = (float)$newShopCart->unit_price * (int)$newShopCart->num;
            $newShopCart->save();
        }

        return response()->json(['level' => 'success','message' => '添加购物车成功','data' => $newShopCart]);
    }

    /**
     * 获取购物车列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getShopCart(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        if(is_null($user->phone) || $user->phone == '')
            return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']);

        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 0;


        /** @var ShopCart $shopCart */
        $shopCarts = ShopCart::whereUserId($user->id)->offset($limit * $page)->limit($limit)->get();
        $isDelete = 0;
        if(count($shopCarts) > 0){
            foreach($shopCarts as $shopCart){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($shopCart->goods_id)->whereIsShop(1)->first();
                if($thisGoods){
                    $thisGoods->thumb_Url = FileManager::getImgUrl($thisGoods->thumb_id);
                }else{
                    $shopCart->delete();
                    $isDelete += 1;
                }

                if($shopCart){
                    $thisGoodsSpu = GoodSpu::whereGoodsId($thisGoods->id)->whereId($shopCart->good_spu_id)->whereStatus(1)->first();
                    if(!$thisGoodsSpu){
                        $shopCart->delete();
                        $isDelete += 1;
                    }

                    if($shopCart){
                        $thisGoods->goods_spu_info = $thisGoodsSpu;
                        $shopCart->goods_info      = $thisGoods;
                    }
                }
            }

        }

        if($isDelete != 0){
            return response()->json(['level' => 'error','message' => '您的购物车中已有'.$isDelete.'件商品被下架']);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $shopCarts]);
    }

    public function deleteShopCart(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        if(is_null($user->phone) || $user->phone == '')
            return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']);

        $shopCartIds = $request->get('shop_cart_ids');

        if(is_array($shopCartIds)){
            foreach($shopCartIds as $shopCartId){
                $thisShopCart = ShopCart::whereId($shopCartId)->whereUserId($user->id)->first();
                if($thisShopCart){
                    $thisShopCart->delete();
                }
            }
        }else{
            return response()->json(['level' => 'error','message' => '数据格式错误']);
        }

        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    /**
     * 用户评论接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userComment(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        if(is_null($user->phone) || $user->phone == '')
            return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']);

        $orderNum = !is_null($request->get('order_num')) ? $request->get('order_num') : 0;
        $goodsId  = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $goodsSpu = !is_null($request->get('goods_spu')) ? $request->get('goods_spu') : 0;
        $content  = !is_null($request->get('content')) ? $request->get('content') : '';
        $imgIds   = $request->get('img_ids');

        /** @var Orders $thisOrders */
        $thisOrders = Orders::whereOrderNum($orderNum)->whereUserId($user->id)->first();
        if(!$thisOrders)
            return response()->json(['level' => 'error','message' => '该订单不存在']);

        /** @var Goods $goods */
        $goods = Goods::whereId($goodsId)->whereIsShop(1)->first();
        if(!$goods)
            return response()->json(['level' => 'error','message' => '商品已下架']);

        if($goods->type == 'integral'){
            /** @var OrderItem $orderItems */
            $orderItems = OrderItem::whereOrderId($thisOrders->id)->whereGoodId($goods->id)->first();
            if(!$orderItems)
                return response()->json(['level' => 'error','message' => '订单错误!']);

            $isComment = Comment::whereUserId($user->id)->whereOrderNum($thisOrders->order_num)->whereGoodsId($goods->id)->first();
            if($isComment)
                return response()->json(['level' => 'error','message' => '您已经评论过订单中的该商品了，请勿重复评论!']);

            $newComment = new Comment();
            $newComment->user_id                   = $user->id;
            $newComment->order_num                 = $thisOrders->order_num;
            $newComment->goods_id                  = $goods->id;
            if($content != '')$newComment->content = $content;
            $newComment->save();
        }elseif($goods->type == 'common'){
            /** @var GoodSpu $thisGoodsSpu */
            $thisGoodsSpu = GoodSpu::whereId($goodsSpu)->first();
            if(!$thisGoodsSpu)
                return response()->json(['level' => 'error','message' => '商品属性不存在']);

            /** @var OrderItem $orderItems */
            $orderItems = OrderItem::whereOrderId($thisOrders->id)->whereGoodId($goods->id)->whereGoodSpuId($thisGoodsSpu->id)->first();
            if(!$orderItems)
                return response()->json(['level' => 'error','message' => '订单错误!']);

            $isComment = Comment::whereUserId($user->id)->whereOrderNum($thisOrders->order_num)->whereGoodsId($goods->id)->whereGoodsSpuId($thisGoodsSpu->id)->first();
            if($isComment)
                return response()->json(['level' => 'error','message' => '您已经评论过订单中的该商品了，请勿重复评论!']);

            $newComment = new Comment();
            $newComment->user_id                   = $user->id;
            $newComment->order_num                 = $thisOrders->order_num;
            $newComment->goods_id                  = $goods->id;
            $newComment->goods_spu_id              = $thisGoodsSpu->id;
            if($content != '')$newComment->content = $content;
            $newComment->save();
        }else{
            return response()->json(['level' => 'error','message' => '系统错误!']);
        }

        if(is_array($imgIds)){
            foreach($imgIds as $imgId){
                $newCommentImg = new CommentImg();
                $newCommentImg->comment_id = $newComment->id;
                $newCommentImg->img_id     = $imgId;
                $newCommentImg->save();
            }
        }else{
            return response()->json(['level' => 'error','message' => '数据格式错误']);
        }

        $orderItems->status = 1;
        $orderItems->save();

        $orderItemNum = OrderItem::whereOrderId($thisOrders->id)->count();

        $ordersCommentNum = Comment::whereUserId($user->id)->whereOrderNum($thisOrders->order_num)->count();

        if($orderItemNum == $ordersCommentNum){
            $thisOrders->status = 5;
            $thisOrders->save();
        }

        return response()->json(['level' => 'success','message' => '评论成功','data' => $newComment]);
    }

    /**
     * 获取评论接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserComment(Request $request){
        $goodsId  = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $limit    = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page     = !is_null($request->get('page')) ? $request->get('page') : 0;
        $isImg    = !is_null($request->get('is_img')) ? $request->get('is_img') : 0;


        /** @var Goods $thisGoods */
        $thisGoods = Goods::whereId($goodsId)->whereIsShop(1)->first();
        if(!$thisGoods)
            return response()->json(['level' => 'error','message' => '商品已下架！']);

        $commentImg = CommentImg::lists('comment_id');

        /** @var Comment $thisUserComment */
        if($isImg != '' && $isImg != 0){
            $thisUserComments = Comment::whereGoodsId($thisGoods->id)->whereIn('id',$commentImg)->orderby('created_at','desc')->offset($limit * $page)->limit($limit)->get();
        }else{
            $thisUserComments = Comment::whereGoodsId($thisGoods->id)->orderby('created_at','desc')->offset($limit * $page)->limit($limit)->get();
        }

        if(count($thisUserComments) > 0){
            foreach($thisUserComments as $thisUserComment){
                /** @var UserInfo $userInfo */
                $userInfo = UserInfo::whereUserId($thisUserComment->user_id)->first();
                if($userInfo){
                    $userInfo->photo_url = FileManager::getImgUrl($userInfo->photo_id);
                }

                $thisUserComment->user_info = $userInfo;

                /** @var CommentImg $thisCommentImg */
                $thisCommentImgs = CommentImg::whereCommentId($thisUserComment->id)->get();
                $commentImageUrls = array();
                if(count($thisCommentImgs) > 0){
                    foreach($thisCommentImgs as $thisCommentImg){
                        $thisCommentImgUrl = FileManager::getImgUrl($thisCommentImg->img_id);
                        array_push($commentImageUrls,$thisCommentImgUrl);
                    }
                }

                $thisUserComment->comment_img = $commentImageUrls;
            }
        }

        $totalCommentNum = Comment::whereGoodsId($thisGoods->id)->count();

        $imageCommentNum = Comment::whereGoodsId($thisGoods->id)->whereIn('id',$commentImg)->count();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thisUserComments,'total_comment_num' => $totalCommentNum,'have_img_comment_num' => $imageCommentNum]);
    }
}
